package com.derbysoft.lowcostadapter.web.action.admin.cachemanager.search;

import com.derbysoft.lowcostadapter.commons.model.RoomStay;
import com.derbysoft.lowcostadapter.commons.redis.service.RoomStayCacheService;
import com.derbysoft.lowcostadapter.commons.redis.utils.KeyValueHelper;
import com.derbysoft.lowcostadapter.web.action.BaseAdapterAction;
import com.derbysoft.lowcostadapter.web.action.model.RoomStayCondition;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by: jason
 * Date: 2012-09-26
 */
public class RoomStaySearchAction extends BaseAdapterAction {

    private RoomStayCondition roomStayCondition;

    @Autowired
    private RoomStayCacheService roomStayCacheService;

    @Action("searchRoomStay")
    public void searchRoomStay() {
        try {
            roomStayCondition.validate();
            List<RoomStay> roomStays = filter(roomStayCacheService.loadAll(roomStayCondition.makeKey()));
            StringBuilder stringBuilder = new StringBuilder();
            for (RoomStay roomStay : roomStays) {
                stringBuilder.append(roomStay.toFiled()).append(KeyValueHelper.SEPARATOR);
                stringBuilder.append(roomStay.value());
                stringBuilder.append("\n");
            }
            process(StringUtils.isBlank(stringBuilder.toString()) ? NOT_FOUND : stringBuilder.toString());
        } catch (Exception e) {
            populateFailedJsonResult(e);
        }
    }

    private List<RoomStay> filter(List<RoomStay> roomStays) {
        List<RoomStay> availRoomStays = new ArrayList<RoomStay>();
        for (RoomStay roomStay : roomStays) {
            if (check(roomStay)) {
                availRoomStays.add(roomStay);
            }
        }
        return availRoomStays;
    }

    private boolean check(RoomStay roomStay) {
        if (StringUtils.isNotBlank(roomStayCondition.getStart())
                && StringUtils.isNotBlank(roomStayCondition.getEnd())) {
            if (roomStayCondition.getStart().compareTo(roomStay.getStart()) < 0
                    || roomStayCondition.getEnd().compareTo(roomStay.getEnd()) > 0) {
                return false;
            }
        }
        return true;
    }

    private void process(String value) {
        try {
            populateSucceededJsonResult(value);
        } catch (Exception e) {
            populateFailedJsonResult(e);
        }
    }

    public RoomStayCondition getRoomStayCondition() {
        return roomStayCondition;
    }

    public void setRoomStayCondition(RoomStayCondition roomStayCondition) {
        this.roomStayCondition = roomStayCondition;
    }
}
